const fs = require('fs');
const ffmpegCommand = require('fluent-ffmpeg');
const options = {
  fileName: 'DANUHD-001-B.mp4',
  filePath: './public/',
  encryptPath: './public/encrypt/'
}
const config = require('./config.js');
const fileName = options.fileName.split('.')[0];
const fileType = options.fileName.split('.')[1];
const encryptedPath = options.encryptPath + fileName;
const videoPath = options.filePath + options.fileName;
const keyInfoPath = './key/key_info.key';
const outputPath = encryptedPath + `/${config.m3u8Name}.m3u8`;
if(!fs.existsSync(encryptedPath)){
  fs.mkdirSync(encryptedPath);
};

if (config.videoType.includes(fileType)) {
    ffmpegCommand(videoPath)
      // .setFfmpegPath('/Users/smith/Desktop/ffmpeg')
      .addOption('-force_key_frames', `expr:gte(t,n_forced*${config.videoDefaultDuration})`)
      .addOption('-hls_time', `${config.videoDefaultDuration}`)   // 设置每个片段的长度
      .addOption('-hls_list_size', '0') // 默认 m3u8 只保存最后五个ts，设置为0 表示保存所有 ts 到 m3u8
      // libx264使用的
      .addOption('-preset', 'veryslow')
      .addOption('-crf', '23')
      // 加密
      .addOption('-hls_key_info_file', keyInfoPath)
      // 设置视频编解码器，不设置的话，手机无法播放
      .videoCodec('libx264')
      .save(outputPath)
      .on('end', function () {
          console.log('Encrypt the ' + options.fileName + ' file OK!');
      })
      .on('stderr', function (stderrLine) {
          console.log('Stderr output: ' + stderrLine);
      })
      .on('error', function (err, stdout, stderr) {
          console.log('Cannot process video: ' + err.message);
      });
} else {
  console.log('type err','file type is not video.');
}